<template>
  <div>
    <el-upload class="avatar-uploader" :action="action" :show-file-list="false" :http-request="toUpload" :accept="accept">
      <div v-if="imageFinish" class="avatar">
        <v-image :src="imageUrl" fit="scale-down" />
      </div>
      <!-- <img v-if="imageUrl" :src="imageUrl" class="avatar" fit="scale-down" /> -->
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <!-- <span class="img-hint" v-if="type == 'video'">图片比例4 : 3</span> -->
  </div>
</template>

<script>
import { domain } from '@/config'
import { getCookie } from '@/utils/tool'
import axios from "axios";
export default {
  data() {
    return {
      imageUrl: this.src,
      imageSwitch: false,
      imageFinish: false,
      accept: this.type == 'video' ? 'video/*' : 'image/*',
      action: ''
    }
  },
  props: ['src', 'isPrivate', 'type'],
  watch: {
    src(val) {
      this.imageFinish = true
      this.$message.success("图片正在完成")
      if (!this.imageSwitch) {
        this.imageUrl = val
      }
    }
  },
  methods: {
    handlePic(file) {
      this.getSrc(file.raw, e => {
        file.raw = this.dataURLtoFile(e, file.name)
        this.$refs.upload.submit()
      })
    },
    clear() {
      this.imageUrl = ''
    },
    toUpload({ file }) {
      this.$message.warning("图片正在上传···")
      this.imageFinish = false
      this.imageSwitch = true
      this.imageUrl = URL.createObjectURL(file);
      let url = this.isPrivate ? `${domain}admin/v1/minio/single/upload` : `${domain}admin/v1/minio/media/upload`
      let headers = {
        Authorization: decodeURIComponent(getCookie('login_ticket')),
        'Content-Type': 'application/x-www-form-urlencoded'
      }
      let data = new FormData()
      if (this.type != 'video') {
        this.getSrc(file, e => {
          file = this.dataURLtoFile(e, file.name)
          data.append('file', file)
          axios({
            headers,
            data,
            method: 'post',
            url,
          }).then(e => {
            this.$emit('avatarPath', e.data.data)
          })
        })
      } else {
        axios({
          headers,
          data,
          method: 'post',
          url,
        }).then(e => {
          this.$emit('avatarPath', e.data.data)
        })
      }
    },
    blobToDataURL(blob, cb) {

      let reader = new FileReader();
      reader.onload = function (evt) {
        let base64 = evt.target.result;
        cb(base64);
      };
      reader.readAsDataURL(blob);

    },
    getSrc(file, cb) {
      let __this = this;
      if (!file) {
        return
      }
      this.percent = 0;
      this.showLoading = true;
      try {
        if (file.size > 1024 * 256) {
          var reader = new FileReader();
          reader.onload = function (e) {
            var image = document.createElement('img');
            image.setAttribute('src', e.target.result);
            image.onload = function () {
              var w = 800,
                canvas = document.createElement('canvas'),
                context = canvas.getContext('2d'),
                imageWidth = 0,    //压缩图片的大小
                imageHeight = 0,
                // offsetX = 0,
                // offsetY = 0,
                data = '';
              if (this.width > this.height) {
                imageWidth = w;
                imageHeight = w * (this.height / this.width);
                canvas.width = w;
                canvas.height = w * (this.height / this.width);
                context.clearRect(0, 0, w, w * (this.height / this.width));
                // offsetY = - Math.round((imageHeight - w) / 2);
              } else {
                imageHeight = w;
                imageWidth = w * (this.width / this.height);
                canvas.width = w * (this.width / this.height);
                canvas.height = w;
                context.clearRect(0, 0, w * (this.width / this.height), w);
                // offsetX = - Math.round((imageWidth - w) / 2);
              }
              // imageWidth = w
              // imageHeight = w * (this.width/this.height)
              context.drawImage(this, 0, 0, imageWidth, imageHeight);
              data = canvas.toDataURL('image/jpeg');
              //压缩完成执行回调
              cb(data);
            };
          }
          reader.readAsDataURL(file);
        } else {
          __this.blobToDataURL(file, cb)
        }
      } catch (e) {
        __this.blobToDataURL(file, cb)
      }

    },
    dataURLtoFile(dataurl, filename) {
      //将base64转换为文件
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
  },
  mounted() {

  }
}
</script>

<style lang="less" scoped>
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

/deep/ .avatar-uploader .el-upload:hover {
  border-color: #4285F4;
}

/deep/ .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
}

/deep/ .el-input-group__append {
  background: #00356B;
  height: 32px;
  width: 108px;
  padding: 0;
}
</style>
